package com.teamtgv.shareshark;

import java.math.BigInteger;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.teamtgv.shareshark.R;
import com.teamtgv.shareshark.location.LocationRetriever;
import com.teamtgv.shareshark.task.InsertRecommendationTask;

public class ShareActivity extends Activity {

	public static final String EVERYONE = "Everyone";
	public static final String LOG_TAG = ShareActivity.class.getSimpleName();
	private static final int CAMERA_REQUEST = 1888;

	private ProgressDialog cameraProgressDialog;
	
	// fields
	private EditText what;
	private EditText where;
	private EditText to;
	private ImageView imageView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Remove title bar
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_share);

		// fields
		what = (EditText) ShareActivity.this.findViewById(R.id.textShareWhat);
		where = (EditText) ShareActivity.this.findViewById(R.id.textShareWhere);
		to = (EditText) ShareActivity.this.findViewById(R.id.textShareTo);
		imageView = (ImageView) ShareActivity.this.findViewById(R.id.imageToShare);

		// Add autocomplete function to "To" field
		ArrayList<String> toPossibilities = new ArrayList<String>();
		toPossibilities.add(EVERYONE);
		toPossibilities.addAll(UserData.getFriendList());

		// make an adapter for the dropdown list
		ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, toPossibilities);
		final AutoCompleteTextView textShareTo = (AutoCompleteTextView) findViewById(R.id.textShareTo);
		textShareTo.setThreshold(1);
		textShareTo.setAdapter(listAdapter);
		textShareTo.setSingleLine();

		// add touch listener to show dropdown menu
		textShareTo.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				textShareTo.showDropDown();
				return false;
			}
		});

		// add camera listener to photo button
		Button photoButton = (Button) this.findViewById(R.id.buttonCamera);
		photoButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				cameraProgressDialog = new ProgressDialog(ShareActivity.this);
				cameraProgressDialog.setMessage("Loading camera...");
				cameraProgressDialog.setIndeterminate(false);
				cameraProgressDialog.setCancelable(false);
				cameraProgressDialog.show();
			    Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(cameraIntent, CAMERA_REQUEST);
			}
		});

		// add location determination to gps button
		final Button gpsButton = (Button) this
				.findViewById(R.id.buttonShareGPS);
		final EditText textWhere = (EditText) this
				.findViewById(R.id.textShareWhere);
		gpsButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Dialog dialog = new Dialog(ShareActivity.this);
				dialog.setTitle("Acquiring location");
				LocationRetriever locationRetriever = new LocationRetriever(
						ShareActivity.this);
				textWhere.setText(locationRetriever.getLocation());
				dialog.dismiss();
			}
		});

		Button shareButton = (Button) this.findViewById(R.id.buttonDoShare);
		shareButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (!allFieldsEntered()) {
					showFieldsAlert();
					return;
				}
				openConfirmDialog();

			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.share, menu);
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	private boolean isEmptyOrBlank(String str) {
		return (str == null || str.trim().length() == 0);
	}

	private boolean allFieldsEntered() {
		EditText what = (EditText) ShareActivity.this
				.findViewById(R.id.textShareWhat);
		EditText where = (EditText) ShareActivity.this
				.findViewById(R.id.textShareWhere);
		EditText to = (EditText) ShareActivity.this
				.findViewById(R.id.textShareTo);
		if (isEmptyOrBlank(what.getText().toString())
				|| isEmptyOrBlank(where.getText().toString())
				|| isEmptyOrBlank(to.getText().toString())) {
			return false;
		}
		return true;
	}

	private void showFieldsAlert() {
		Toaster.showToast(ShareActivity.this, "Please enter all fields");
	}

	private void openConfirmDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(
				ShareActivity.this);
		builder.setMessage(R.string.dialog_share_confirmation);
		builder.setPositiveButton(R.string.yes,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User clicked OK button
						dialog.dismiss();
						
						addShareToDatabase();
						ShareActivity.this.finish();
					}
				});
		builder.setNegativeButton(R.string.no,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});
		AlertDialog dialog = builder.create();
		dialog.show();
	}

	private void addShareToDatabase() {
		Log.v(LOG_TAG, "Adding share to database");
		
		String target = to.getText().toString();
		
		BigInteger targetId;
		if (target.equals(EVERYONE))
			targetId = new BigInteger("-1");
		else
			targetId = UserData.getFriendId(target);
		
		if (targetId == null) {
			Toaster.showToast(this, "Contact does not appear in friendlist");
			return;
		}
			
		
		InsertRecommendationTask insertTask = new InsertRecommendationTask(this, what.getText().toString(), where.getText().toString(), targetId);
		insertTask.execute();
		Integer id = null;
		try {
			id = insertTask.get();
			Toaster.showToast(this, "Shared!");
			Log.v(LOG_TAG, "Share created with id " + id);
		} catch (Exception e) {
			Toaster.showToast(this, "Failed to share, try again soon.");
			Log.v(LOG_TAG, "Failed to share: " + e.toString() + ": " + e.getMessage());
		}
		if (id != null && imageView.getVisibility() == View.VISIBLE) {
			Log.i(LOG_TAG, "Share contains image");
			BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
			Bitmap bitmap = drawable.getBitmap();
			try {
				ImageShack imageShack = new ImageShack();
				Log.v(LOG_TAG, "Making call to upload function for ImageShack");
				imageShack.upload(bitmap, id);
				
			} catch (Exception e) {
				Log.e(LOG_TAG, "Exception occured during uploading the image: " + e.toString() + " - " + e.getMessage());
			}
		}
	}

	// Handle returning intent from camera button
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		cameraProgressDialog.dismiss();
		if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
			ImageView imageView = (ImageView) this
					.findViewById(R.id.imageToShare);
			Button photoButton = (Button) this.findViewById(R.id.buttonCamera);
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			imageView.setImageBitmap(photo);
			photoButton.setVisibility(View.INVISIBLE);
			imageView.setVisibility(View.VISIBLE);
		}
	}

}
